##
##

package Purl::Commands::file;
use strict;

use Purl::Config;
use Purl::Template; 

sub import {

    # Register the commands when they are loaded into the system
    Purl::Commands::register(
        name   => "news",
        subRef => \&Purl::Commands::file::cmd_news,
    );

    Purl::Commands::register(
        name   => "help",
        subRef => \&Purl::Commands::file::cmd_help,
    );

    Purl::Commands::register(
        name   => "motd",
        subRef => \&Purl::Commands::file::motd,
    );

}

{

    sub _getFromFormattedFile {
        my ( $fileKey, $fromFile ) = @_;
        if ( !open( IN, $fromFile ) ) {
            Purl::comm::tellWizards(
                "ERROR: the file " . $fromFile . " is missing." );
            return;
        }

        my $found = 0;
        while (<IN>) {
            s/\s+$//;
            if ( $fileKey eq $_ ) {
                $found = 1;
                last;
            }
        }
        if ( !$found ) {
            return
                "Sorry, there is no such news topic. Try just typing news.";
            close(IN);
            return;
        }
        my $return;
        while (<IN>) {
            s/\s+$//;
            last if ( substr( $_, 0, 1 ) eq "&" );
            $return .= $_ . "\n";
        }
        close(IN);

        return $return;
    }

}

sub cmd_news {
    my %args = @_;
    my %tData;
    $tData{template} = "basicText";
    my ($found);
    $args{text}  = "index" if ( $args{text} eq "" );
    $args{text}  = "& " . $args{text};
    $tData{text} = _getFromFormattedFile( $args{text}, config("newsfile") );
    my $text = processTemplate(%tData);
    print $text;
}

sub cmd_help {
    my %args = @_;
    my %tData;
    $tData{template} = "basicText";
    my ($found);
    $args{text}  = "index" if ( $args{text} eq "" );
    $args{text}  = "& " . $args{text};
    $tData{text} = _getFromFormattedFile( $args{text}, config("helpfile") );
    my $text = processTemplate(%tData);
    print $text;
}

sub motd {
    my %args = @_;
    Purl::comm::sendFile( $args{actor}, config("motdfile") );
}

sub welcome {
    my %args = @_;
    Purl::comm::sendFile( $args{actor}, config("welcomefile") );
}

1;
